const LogModel = require('../../model/Log');
const moment = require('moment')
const Reimburse = require('../../model/Reimburse')
const ProductSub = require('../../model/ProductSub')
const Voucher = require('../../model/Voucher')
const Order = require('../../model/Order')
const MyVoucher = require('../../model/MyVoucher');
const PointHistory = require('../../model/PointHistory')
const MemberCard = require('../../model/MemberCard')
const UserPoint = require('../../model/userPoint')
const Member = require('../../model/Member')
var wxpay = require('../../util/wxpay')
const wxPublicAccessToken = require('../../util/businessUtil/wxPublicAccessToken')

module.exports = {

    getReimburseList: async (req, res, next) => {
        try {
            if (req.body.createdStart) {
                var createdStart = new Date(req.body.createdStart)
            }
            if (req.body.createdEnd) {
                var createdEnd = new Date(req.body.createdEnd)
            }
            if (req.body.updatedStart) {
                var updatedStart = new Date(req.body.updatedStart)
            }
            if (req.body.updatedEnd) {
                var updatedEnd = new Date(req.body.updatedEnd)
            }
            let option = {}
            option.isDelete = 0
            if (req.body.cellphoene) {
                let user = await User.findOne({ cellphoene: new RegExp(req.body.cellphoene, 'i'), isDelete: 0 }).exec()
                option.openid = user.openid
            }
            if (req.body.order) {
                option.order = req.body.order
            }
            if (req.body.shipping) {
                option.shipping = req.body.shipping
            }
            if (req.body.status) {
                option.status = req.body.status
            }
            if (req.body.reason) {
                option.reason = new RegExp(req.body.reason, 'i')
            }
            if (req.body.comment) {
                option.comment = new RegExp(req.body.comment, 'i')
            }
            if (createdStart && !createdEnd) {
                option.createdAt = { $gte: createdStart }
            } else if (!createdStart && createdEnd) {
                option.createdAt = { $lte: createdEnd }
            } else if (createdStart && createdEnd) {
                option.$and = [{ createdAt: { $gte: createdStart } }, { createdAt: { $lte: createdEnd } }]
            }
            if (updatedStart && !updatedEnd) {
                option.updatedAt = { $gte: updatedStart }
            } else if (!updatedStart && updatedEnd) {
                option.updatedAt = { $lte: updatedEnd }
            } else if (updatedStart && updatedEnd) {
                option.$and = [{ updatedAt: { $gte: updatedStart } }, { updatedAt: { $lte: updatedEnd } }]
            }
            let count = await Reimburse.countDocuments(option).exec()
            let page = req.body.page || 1
            let pageSize = req.body.pageSize || count
            let data = await Reimburse.find(option).skip((page - 1) * pageSize).limit(pageSize).sort({ index: 1 }).populate('order shipping').exec()
            let result = {}
            result.total = count
            result.currentPage = page
            result.data = data
            result.pageSize = pageSize
            res.ok('获取成功', result)
        } catch (e) {
            next(e)
        }
    },
    approveReimburse: async (req, res, next) => {
        try {
            let reimburse = await Reimburse.findOne({ _id: req.body.id, isDelete: 0 }).populate('order').exec()
            if (reimburse.order.total == 0) {
                approveReimburseProcess(req.body.id, req, res)
            } else {
                // wxpay.reimburse(reimburse._id,reimburse.order._id,reimburse.order.total,reimburse.order.total,function(err,response,body){
                // 		if ((body.return_code[0] == 'SUCCESS') && (body.result_code[0] == 'SUCCESS')){
                approveReimburseProcess(req.body.id, req, res)
                // 		}
                // 		else if ((body.return_code[0] == 'SUCCESS') && (body.result_code[0] == 'FAIL')){
                //             res.send({code:201,msg:"微信退款失败",data:body})
                // 		}
                // 		else{
                //             res.send({code:201,msg:"微信退款失败",data:body})
                // 		}
                // })
            }
        } catch (e) {
            next(e)
        }
    },

    rejectReimburse: async (req, res, next) => {
        try {
            let reimburse = await Reimburse.findOne({ _id: req.body.id, isDelete: 0 }).exec()
            reimburse.status = 2
            await reimburse.save()//need fix 拒绝后的处理
            res.ok('拒绝退款')
        } catch (e) {
            next(e)
        }
    },

    changeReimburse: async (req, res, next) => {
        try {
        } catch (e) {
            next(e)
        }
    },

    getOneReimburse: async (req, res, next) => {
        try {
            let reimburse = await Reimburse.findOne({ _id: req.body.id, isDelete: 0 }).populate({ path: 'order', model: Order, populate: { path: 'products.product', model: ProductSub } }).populate({ path: 'order', model: Order, populate: { path: 'products.voucher', model: Voucher } }).exec()
            res.ok('查询成功', reimburse)
        } catch (e) {
            next(e)
        }
    },
};

async function approveReimburseProcess(id, req, res) {
    let reimburse = await Reimburse.findOne({ _id: req.body.id, isDelete: 0 }).exec()
    reimburse.status = 1
    await reimburse.save()
    let order = await Order.findOne({ _id: reimburse.order, isDelete: 0 }).exec()
    if (order.type == 0) {
        if (order.usePoint == 1) {
            let newPointHistory = new PointHistory({
                openid: order.openid,
                unionID: order.unionID,
                order: order._id,
                expenseDate: new Date(),
                manual: 0, // 1位人工，0为自动
                amount: order.amountOfUsePoint, // 变动的积分数量
                type: 0, // 0 为加，1为减
                isDelete: 0,
            })
            await newPointHistory.save()
            let memberCardNumber = (await MemberCard.findOne({ isDelete: 0 }).exec()).cardId
            let member = await Member.findOne({ openid: order.openid, isDelete: 0 }).exec()
            let userPoint = await UserPoint.findOne({ openid: order.openid, isDelete: 0 }).exec()
            member.point = member.point + order.amountOfUsePoint
            member.updatedAt = new Date()
            await member.save()
            userPoint.current = userPoint.current + order.amountOfUsePoint
            userPoint.updatedAt = new Date()
            await userPoint.save()
            order.status = 2
            await order.save()
            wxPublicAccessToken.getAccessToken(function (token) {
                request({
                    url: 'https://api.weixin.qq.com/card/membercard/updateuser?access_token=' + token,
                    method: "POST",
                    timeout: 10000,
                    encoding: null,
                    json: {
                        "code": member.code,
                        "card_id": memberCardNumber,
                        "bonus": member.point
                    }
                }, function (error, response, body) {
                    console.log(error)
                    res.ok('同意退款')
                })
            })
        } else {
            order.status = 2
            await order.save()
            res.ok('同意退款')
        }
    } else if (order.type == 1) {
        myVoucher = await MyVoucher.find({ order: order._id }).exec()
        for (let i = 0; i < myVoucher.length; i++) {
            myVoucher[i].isDelete = 1
            myVoucher[i].updatedAt = new Date()
            await myVoucher[i].save()
        }
        order.status = 2
        await order.save()
        if (order.usePoint == 1) {
            let newPointHistory = new PointHistory({
                openid: order.openid,
                unionID: order.unionID,
                order: order._id,
                expenseDate: new Date(),
                manual: 0, // 1位人工，0为自动
                amount: order.amountOfUsePoint, // 变动的积分数量
                type: 0, // 0 为加，1为减
                isDelete: 0,
            })
            await newPointHistory.save()
            let memberCardNumber = (await MemberCard.findOne({ isDelete: 0 }).exec()).cardId
            let member = await Member.findOne({ openid: order.openid, isDelete: 0 }).exec()
            let userPoint = await UserPoint.findOne({ openid: order.openid, isDelete: 0 }).exec()
            member.point = member.point + order.amountOfUsePoint
            member.updatedAt = new Date()
            await member.save()
            userPoint.current = userPoint.current + order.amountOfUsePoint
            userPoint.updatedAt = new Date()
            await userPoint.save()
            wxPublicAccessToken.getAccessToken(function (token) {
                request({
                    url: 'https://api.weixin.qq.com/card/membercard/updateuser?access_token=' + token,
                    method: "POST",
                    timeout: 10000,
                    encoding: null,
                    json: {
                        "code": member.code,
                        "card_id": memberCardNumber,
                        "bonus": member.point
                    }
                }, function (error, response, body) {
                    console.log(error)
                    res.ok('同意退款')
                })
            })
        }
        res.ok('同意退款')
    }
}